package com.labichaoka.chaoka.net;

import android.util.Log;

import com.google.gson.JsonParseException;
import com.labichaoka.chaoka.entity.ApiException;
import com.labichaoka.chaoka.utils.NetworkUtil;
import com.labichaoka.chaoka.utils.ToastUtils;

import org.json.JSONException;

import java.net.ConnectException;
import java.text.ParseException;

import retrofit2.HttpException;
import rx.Subscriber;

public abstract class BaseSubscriber<T> extends Subscriber<T> {

    //对应HTTP的状态码
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    @Override
    public void onStart() {
        if (!NetworkUtil.isNetworkAvailable()){
            this.onError(new ApiException(999,"请检查您的网络是否连接！"));
            return;
        }
    }

    @Override
    public void onCompleted() {
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch(httpException.code()){
                case GATEWAY_TIMEOUT:
                    ToastUtils.show("连接服务器超时！");
                    break;
                default:
                    ToastUtils.show("服务器异常！");
                    break;
            }

        } else if (e instanceof ConnectException) {
            ToastUtils.show("请检查您的网络是否连接!");

        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            ToastUtils.show("数据解析错误!");

        } else if (e instanceof ApiException) {
            //ApiException exception = (ApiException) e;
            Log.e("ruan",e.getMessage());
            ToastUtils.show(e.getMessage());

        }

    }

    @Override
    public void onNext(T t) {

    }
}
